﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MoPhongLapLich
{
    class Resource1 : IAddQueue, IRunable
    {

        private LinkedList<Process> _processes;
        private List<IAddQueue> _link;
        private Process _processing;

        public Resource1()
        {
            _link = new List<IAddQueue>();
            _processes = new LinkedList<Process>();
        }

        #region Implementation of IAddQueue

        public void Add(Process pro)
        {
            if (pro.GetR1() != 0 && !pro.IsProcessing)
            {
                _processes.AddFirst(pro);
                pro.IsProcessing = true;
                //Console.Write("{0}:P{1}  In",Glogal.GlogalTime,pro.Id);
                //PrintDebug();Console.WriteLine();
            }
        }

        public void AddLink(IAddQueue link)
        {
            _link.Add(link);
        }

        #endregion

        #region Implementation of IRunable
        public void PrintDebug()
        {
            Console.Write("\t\t queue");
            foreach (var process in _processes)
            {
                Console.Write("P{0},", process.Id);
            }
        }
        public void Run(object source, TickEventArgs e)
        {
            int tick = e.TickTime;
            if(_processes.Count==0) return;

            if(_processing==null)
            {
                _processing = _processes.First.Value;
                foreach (var process in _processes)
                {
                    if ( process.GetR1() < _processing.GetR1()) _processing = process;
                }
            }

            _processing.DecR1();
            //AddTimeWait(_processing);
            if(_processing.GetR1()==0)
            {
                //Console.Write("{0}:P{1}  Out", tick, _processing.Id);
                //PrintDebug(); Console.WriteLine();
                _processing.IsProcessing = false;
                foreach (IAddQueue addQueue in _link)
                {
                    addQueue.Add(_processing);
                }
                _processes.Remove(_processing);
                _processing = null;
            }

        }

        #endregion

        public void AddTimeWait(Process processing)
        {
            foreach (var process in _processes)
            {
                if (process != processing)
                {
                    process.AddTimewait();
                }
            }
        }
    }
}
